﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlobDownloader
{
    public static class ArgumentsParser
    {
        public static IDictionary<TKey, TValue> TryRemove<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key)
        {
            if (source.ContainsKey(key))
            {
                source.Remove(key);
            }
            return source;
        }

        public static IDictionary<TKey, TValue> Clone<TKey, TValue>(this IDictionary<TKey, TValue> source)
        {
            return source.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }

        public static bool TryGetValueByKeys<TKey, TValue>(this IDictionary<TKey, TValue> source, out TValue value, params TKey[] keys)
        {
            value = default(TValue);

            if (keys == null || !keys.Any())
            {
                return false;
            }

            var values = keys
                .Where(k => source.ContainsKey(k))
                .Select(k => source[k])
                .ToList();
            if (values.Any())
            {
                value = values.First();
                return true;
            }
            else
            {
                return false;
            }
        }

        public static TValue TryGetValueOrDefaultByKeys<TKey, TValue>(this IDictionary<TKey, TValue> source, TValue defaultValue, params TKey[] keys)
        {
            var value = default(TValue);
            if (!TryGetValueByKeys<TKey, TValue>(source, out value, keys))
            {
                value = defaultValue;
            }
            return value;
        }

        public static IDictionary<string, string> ToArguments(string[] args)
        {
            var arguments = new Dictionary<string, string>();
            for (var i = 0; i < args.Length; i++)
            {
                if (args[i][0] == '/' || args[i][0] == '-')
                {
                    var j = i + 1;
                    arguments[args[i]] = j < args.Length ? args[j] : string.Empty;
                    i++;
                }
            }
            return arguments;
        }

        public static string ToString(IDictionary<string, string> arguments)
        {
            var sb = new StringBuilder();
            foreach (var arg in arguments)
            {
                sb.AppendFormat("{0} {1} ", arg.Key, arg.Value);
            }
            return sb.ToString();
        }
    }
}
